//
//  KZRingBanner.swift
//  BoyeStore
//
//  Created by 朱凯 on 2018/6/23.
//  Copyright © 2018年 itboye. All rights reserved.
//

import UIKit

class KZRingBannerItem: KZBaseModel {
    
    var imgID: Int = 0          // 图片显示
    var title: String = ""      // 标题
    var urlStr: String = ""     // 点击前往的地址(一般轮播需要点击)
    
    enum CodingKeys: String, CodingKey {
        case imgID
        case title
        case urlStr
    }
    
    var imgUrl: URL? {
        return URL.init(string: "\(imgID)")
    }
    
    var checkCode: String {
        return "\(imgID)" + "\(title)" + "\(urlStr)"
    }
}

import RxCocoa
import RxSwift


// MARK: ------ 循环的轮播图
class KZRingBanner: UIView {
   
    let bag = DisposeBag()
    
    var items: [KZRingBannerItem] = [KZRingBannerItem]() { didSet {
        // 根据checkCode是否完全一致，来判断两个bannerItem是否相同
        // 如果items和oldValue全部相同，则不用刷新
        if items.elementsEqual(oldValue, by: { (item1, item2) -> Bool in
            return item1.checkCode == item2.checkCode
        }) {
            return
        }
        
        setNeedsLayout() } }
    var duration: TimeInterval = 3 { didSet { setNeedsLayout() } }
    
    let scroll = UIScrollView()
    let pageControl = UIPageControl()
    var timer: Timer? = nil
    
    
    deinit {
        print("banner销毁")
    }
 
    convenience init() {
        self.init(frame: .zero)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// MARK: ------ 布局
extension KZRingBanner {
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        guard items.count > 0 else {
            return
        }
        
        if timer != nil {
            timer!.invalidate()
            timer = nil
        }
        
        for subview in scroll.subviews {
            subview.removeFromSuperview()
        }
        
        pageControl.numberOfPages = items.count
        pageControl.currentPage = 0
        
        // 创建图片
        var last: UIImageView? = nil
        for (i, item) in items.enumerated() {
            
            let view = UIImageView()
            view.kf.setImage(with: item.imgUrl)
            scroll.addSubview(view)
            view.backgroundColor = i == 0 ? kRedColor : kBlueColor
            view.snp.makeConstraints { (m) in
                m.left.equalTo(last?.snp.right ?? 0)
                m.size.equalTo(scroll)
                m.top.equalTo(0)
            }

            last = view
        }
        
        // 最后一张图片
        let lastView = UIImageView()
        lastView.kf.setImage(with: items.last!.imgUrl)
        lastView.backgroundColor = kRedColor
        scroll.addSubview(lastView)
        lastView.snp.makeConstraints { (m) in
            m.left.equalTo(last!.snp.right)
            m.top.size.equalTo(last!)
            
            m.right.equalTo(0)
        }
        
        scroll.layoutIfNeeded()
        // 添加定时器
        timer = Timer.scheduledTimer(timeInterval: duration, target: self, selector: #selector(onTimerAction(_:)), userInfo: nil, repeats: true)
        RunLoop.main.add(timer!, forMode: .commonModes)
    }
    
    private func setupUI() {
        
        self.addSubview(scroll)
        scroll.bounces = false
        scroll.isPagingEnabled = true
        scroll.showsHorizontalScrollIndicator = false
        scroll.snp.makeConstraints { (m) in
            m.edges.equalTo(self)
        }
        
        scroll.rx
            .didEndDecelerating
            .bind { [weak self] in
                
                guard let wself = self else {
                    return
                }
                
                // 移到了最后一个
                if wself.scroll.contentOffset.x == (wself.scroll.contentSize.width - wself.scroll.width) {
                    wself.scroll.contentOffset = CGPoint(x: 0, y: 0)
                }
                // 设置page
                wself.pageControl.currentPage = floor(wself.scroll.contentOffset.x / wself.scroll.width).int

            }
            .disposed(by: bag)
        
        
        self.addSubview(pageControl)
        pageControl.pageIndicatorTintColor = UIColor.white
        pageControl.currentPageIndicatorTintColor = kThemeColor
        pageControl.snp.makeConstraints { (m) in
            m.height.equalTo(40)
            m.right.equalTo(-20)
            m.bottom.equalTo(-10)
        }
    }
    
}


// MARK: ------ 事件
extension KZRingBanner {
    
    // 定时器事件
    @objc func onTimerAction(_ timer: Timer) {
    
        UIView.animate(withDuration: 0.25, animations: {
            self.scroll.contentOffset.x = self.scroll.contentOffset.x + self.scroll.width
        }) { (fin) in
            
            // 移到了最后一个
            if self.scroll.contentOffset.x >= (self.scroll.contentSize.width - self.scroll.width) {
                self.scroll.contentOffset.x = 0
            }
            
            // 设置page
            self.pageControl.currentPage = floor(self.scroll.contentOffset.x / self.scroll.width).int
        }
    }
}


